package com.jumi.microservice.service.impl;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosAlert;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jumi.microservice.config.JPushConfig;
import com.jumi.microservice.service.JPushService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.LinkedList;
import java.util.Map;

/**
 * @Description
 * @ClassName JPushServiceImpl
 * @Author Abel Yang
 * @Date 2020/10/23/023 16:15
 **/
@Service
public class JPushServiceImpl implements JPushService {

    @Resource
    private JPushConfig jPushConfig;

    private static final Logger log = LoggerFactory.getLogger(JPushServiceImpl.class);

    //极光推送>>Android
    //Map<String, String> parm是我自己传过来的参数,可以自定义参数
    public void jpushAndroid(Map<String, String> parm) {
        //创建JPushClient(极光推送的实例)
        JPushClient jpushClient = new JPushClient(jPushConfig.getMasterSecret(), jPushConfig.getAppKey());
        //推送的关键,构造一个payload
        PushPayload payload = PushPayload.newBuilder()
                .setPlatform(Platform.android())//指定android平台的用户
                .setAudience(Audience.all())//你项目中的所有用户
//                .setAudience(Audience.alias(parm.get("alias")))//设置别名发送,单发，点对点方式
                //.setAudience(Audience.tag("tag1"))//设置按标签发送，相当于群发
//                .setAudience(Audience.registrationId(parm.get("id")))//registrationId指定用户

                .setNotification(Notification.android(parm.get("msg"), parm.get("title"), parm))  //发送内容
                .setOptions(Options.newBuilder().setApnsProduction(true).setTimeToLive(7200).build())
                // apnProduction指定开发环境 true为生产模式 false 为测试模式 (android不区分模式,ios区分模式) 不用设置也没关系
                // TimeToLive 两个小时的缓存时间
                .setMessage(Message.content(parm.get("msg")))//自定义信息
                .build();

        try {
            PushResult pu = jpushClient.sendPush(payload);
            System.out.println(pu.toString());
        } catch (APIConnectionException e) {
            e.printStackTrace();
        } catch (APIRequestException e) {
            e.printStackTrace();
        }
    }

    //极光推送>>ios
    //Map<String, String> parm是我自己传过来的参数,可以自定义参数
    public void jpushIOS(Map<String, String> parm) {
        //创建JPushClient
        JPushClient jpushClient = new JPushClient(jPushConfig.getMasterSecret(), jPushConfig.getAppKey());
        PushPayload payload = PushPayload.newBuilder()
                .setPlatform(Platform.ios())//ios平台的用户
                .setAudience(Audience.all())//所有用户
                //.setAudience(Audience.registrationId(parm.get("id")))//registrationId指定用户
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(parm.get("msg"))
                                .setBadge(+1)
                                .setSound("happy")//这里是设置提示音(更多可以去官网看看)
                                .addExtras(parm)
                                .build())
                        .build())
                .setOptions(Options.newBuilder().setApnsProduction(false).build())
                .setMessage(Message.newBuilder().setMsgContent(parm.get("msg")).addExtras(parm).build())//自定义信息
                .build();

        try {
            PushResult pu = jpushClient.sendPush(payload);
            System.out.println(pu.toString());
        } catch (APIConnectionException e) {
            e.printStackTrace();
        } catch (APIRequestException e) {
            e.printStackTrace();
        }
    }


    //极光推送>>All所有平台
    @Override
    public String pushAll(Map<String, String> params,Integer unreadNum) {
        //遍历设备号
        Collection<String> list = new LinkedList<String>();
        String[] Registerid = params.get("id").split(",");
        for (int i = 0; i < Registerid.length; i++) {
            list.add(Registerid[i]);
        }
        //创建一个IosAlert对象，可指定APNs的alert、title等字段
        IosAlert iosAlert = IosAlert.newBuilder().setTitleAndBody(params.get("title"), "",params.get("msg")).build();
        //创建JPushClient
        JPushClient jpushClient = new JPushClient(jPushConfig.getMasterSecret(), jPushConfig.getAppKey());
        //创建option
        PushPayload payload = PushPayload.newBuilder()
                .setPlatform(Platform.all())  //所有平台的用户
                .setAudience(Audience.registrationId(list))//registrationId指定用户
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(IosNotification.newBuilder() //发送ios
                                .setAlert(iosAlert) //消息体
                                .setBadge(+unreadNum)
                                .setSound("happy") //ios提示音
                                .addExtras(params) //附加参数
                                .build())
                        .addPlatformNotification(AndroidNotification.newBuilder() //发送android
                                .setAlert(params.get("msg")) //消息体
                                .setTitle(params.get("title"))//通知标题
                                .addExtras(params) //附加参数
                                .addCustom("uri_activity", params.get("uri_activity"))
                                .addCustom("uri_action", params.get("uri_action"))
                                .addCustom("badge_add_num", 1)
                                .addCustom("badge_class",  "com.jumi.groupbuy.Activity.StartActivity")
                                .build())
                        .build())
                .setOptions(Options.newBuilder().setApnsProduction(jPushConfig.isDevelopScene()).build())//指定开发环境 true为生产模式 false 为测试模式 (android不区分模式,ios区分模式)
                .setMessage(Message.newBuilder().setMsgContent(params.get("msg")).addExtras(params).build())//自定义信息
                .build();
        try {
            log.info("指定用户设备推送:"+ JSON.toJSONString(params));
            PushResult pu = jpushClient.sendPush(payload);
            System.out.println(pu.toString());
            return pu.toString();
        } catch (APIConnectionException e) {
            e.printStackTrace();
        } catch (APIRequestException e) {
            e.printStackTrace();
        }
        return null;
    }

    //极光推送>>All所有平台,所有用户
    @Override
    public String pushUserAll(Map<String, String> params) {
        //创建JPushClient
        JPushClient jpushClient = new JPushClient(jPushConfig.getMasterSecret(), jPushConfig.getAppKey());
        //创建一个IosAlert对象，可指定APNs的alert、title等字段
        IosAlert iosAlert = IosAlert.newBuilder().setTitleAndBody(params.get("title"), "",params.get("msg")).build();
        Audience audience;
        if(jPushConfig.isDevelopScene()){
             audience = Audience.all();
        }else {
             audience = Audience.registrationId("1517bfd3f7756a62044","13065ffa4e87ef6932e");
        }
        //创建option
        PushPayload payload = PushPayload.newBuilder()
                .setPlatform(Platform.all())  //所有平台的用户
                // TODO: 2020/12/9 测试用设备号id暂时写死 
                .setAudience(audience)//registrationId指定用户
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(IosNotification.newBuilder() //发送ios
                                .setAlert(iosAlert) //消息体
                                .setBadge(+0)
                                .setSound("happy") //ios提示音
                                .addExtras(params) //附加参数
                                .build())
                        .addPlatformNotification(AndroidNotification.newBuilder() //发送android
                                .setAlert(params.get("msg")) //消息体
                                .setTitle(params.get("title"))//通知标题
                                .addExtras(params) //附加参数
                                .addCustom("uri_activity", params.get("uri_activity"))
                                .addCustom("uri_action", params.get("uri_action"))
                                .build())
                        .build())
                .setOptions(Options.newBuilder().setApnsProduction(jPushConfig.isDevelopScene()).build())//指定开发环境 true为生产模式 false 为测试模式 (android不区分模式,ios区分模式)
                .setMessage(Message.newBuilder().setMsgContent(params.get("msg")).addExtras(params).build())//自定义信息
                .build();
        try {
            log.info("所有用户设备推送:"+ JSON.toJSONString(params));
            PushResult pu = jpushClient.sendPush(payload);
            System.out.println(pu.toString());
            return pu.toString();
        } catch (APIConnectionException e) {
            e.printStackTrace();
        } catch (APIRequestException e) {
            e.printStackTrace();
        }
        return null;
    }
}
